<!--
 * @Description: 
 * @Version: 1.0.1
 * @Autor: hrlu.cn
 * @Date: 2022-02-27 21:44:06
 * @LastEditors: hrlu.cn
 * @LastEditTime: 2022-03-20 16:53:07
-->
{% extends "base.html" %}

{% block cssextend %}
    <link href="/assets/vendor/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <link href="/assets/css/bootstrap-table-custom.css" rel="stylesheet">
{% endblock %}

{% block cssstyle %}
{% endblock %}

{% block content %}
     <!-- DATA TABLE-->
     <section class="p-t-20">
        <div class="container">
            <div class="row">
                <div class="col-sm-12">
                    <div class="statistic-chart-1">
                        <h3 class="title-3 m-b-10">十大流通股东情况概览</h3>
                        
                        <table id="top10-holder-table" class="table table-hover">
                            <thead>
                                <tr>
                                    <th data-field="scode" data-sortable="true">股票代码</th>
                                    <th data-align="center" data-field="sname" data-sortable="true">股票名称</th>
                                    <th data-align="center" data-field="industry" data-sortable="true">所属行业</th>
                                    <th data-align="center" data-field="concepts" data-sortable="true" data-formatter="textOverFlowDisplay">概念分类</th>
                                    <!--th data-align="center" data-field="quarter" data-sortable="true">季度</th-->
                                    <!--th data-align="center" data-field="report_date" data-sortable="true">公告日期</th-->
                                    <!--th data-align="center" data-field="prop_change" data-sortable="true">占比差</th-->
                                    <th data-align="center" data-field="new_holder_count" data-sortable="true">新晋股东</th>
                                    <th data-align="center" data-field="new_holder_prop" data-sortable="true">新晋占比</th>
                                    <!--th data-align="center" data-field="new_fund_count" data-sortable="true">新晋基金股东</th-->
                                    <!--th data-align="center" data-field="new_fund_prop" data-sortable="true">新晋基金占比</th-->
                                    <th data-align="center" data-field="add_holder_count" data-sortable="true">增持股东</th>
                                    <th data-align="center" data-field="add_holder_prop" data-sortable="true">增持占比</th>
                                    <th data-align="center" data-field="reduce_holder_count" data-sortable="true">减持股东</th>
                                    <th data-align="center" data-field="reduce_holder_prop" data-sortable="true">减持占比</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-12">
                    <div class="statistic-chart-1">
                        <h3 class="title-3 m-b-10">组合持股情况概览</h3>
                        
                        <table id="combine-holder-table" class="table table-hover">
                            <thead>
                                <tr>
                                    <th data-field="combine_name" data-sortable="true">组合名称</th>
                                    <th data-field="count" data-sortable="true">持股个数</th>
                                    <th data-field="hold_amount" data-sortable="true">持股市值</th>
                                    <th data-field="fixed_list" data-sortable="false" data-formatter="textOverFlowDisplay">不变股票</th>
                                    <th data-field="added_list" data-sortable="false" data-formatter="textOverFlowDisplay">增持股票</th>
                                    <th data-field="reduced_list" data-sortable="false" data-formatter="textOverFlowDisplay">减持股票</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-5">
                    <div class="statistic-chart-1">
                        <h3 class="title-3 m-b-10">自然人持股情况</h3>
                        
                        <table id="holder-shareholding-table" class="table table-hover">
                            <thead>
                                <tr>
                                    <th data-field="holder" data-sortable="true">自然人姓名</th>
                                    <th data-align="center" data-field="count" data-sortable="true">持股数量</th>
                                    <th data-align="center" data-field="hold_amount" data-sortable="true">持股市值</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
                <div class="col-sm-7">
                    <div class="statistic-chart-1">
                        <h3 class="title-3 m-b-10">牛散持股情况</h3>
                        
                        <table id="stock-legend-holder-table" class="table table-hover">
                            <thead>
                                <tr>
                                    <th data-field="scode" data-sortable="true">股票代码</th>
                                    <th data-align="center" data-field="sname" data-sortable="true">股票名称</th>
                                    <th data-align="center" data-field="industry" data-sortable="true">所属行业</th>
                                    <th data-align="center" data-field="concepts" data-sortable="true" data-formatter="textOverFlowDisplay">概念分类</th>
                                    <th data-align="center" data-field="count" data-sortable="true">该股的牛散数量</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>  
        </div>
    </section>
    <div id="top10-holder-toolbar">
        <div class="input-group">
            <select class="form-control form-control-sm" tabindex="-1" name="quarter" id="top10HolderQuarterSelect">
                {% for p in holding_periods %}
                    <option value="{{ p }}">{{ p }}</option>
                {% endfor %}
            </select>
        </div>
    </div>
    <div id="combine-holder-toolbar">
        <div class="input-group">
            <select class="form-control form-control-sm" tabindex="-1" name="quarter" id="combineHolderQuarterSelect">
                {% for p in holding_periods %}
                    <option value="{{ p }}">{{ p }}</option>
                {% endfor %}
            </select>
            <!--button class="form-control form-control-sm" onclick="document.getElementById('combineFileChoice').click()">上传关键词</button>
            <input type="file" id="combineFileChoice" style="display: none;"-->
            <button class="form-control form-control-sm" onclick="initializeCombinedKeywords()">配置关键词</button>
        </div>
    </div>
    <div id="top-legend-holder-toolbar">
        <div class="input-group">
            <select class="form-control form-control-sm" tabindex="-1" name="quarter" id="legendHolderQuarterSelect">
                {% for p in holding_periods %}
                    <option value="{{ p }}">{{ p }}</option>
                {% endfor %}
            </select>
        </div>
    </div>
    <div id="stock-legend-holder-toolbar">
        <div class="input-group">
            <select class="form-control form-control-sm" tabindex="-1" name="quarter" id="stockLegendHolderQuarterSelect">
                {% for p in holding_periods %}
                    <option value="{{ p }}">{{ p }}</option>
                {% endfor %}
            </select>
        </div>
    </div>

    <div class="modal fade" id="top10HoldersModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">十大流通股东</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <table class="table bootstrap-table" id="top10HoldersModalTable">
                        <thead>
                            <tr>
                                <th>持有人</th>
                                <th>持股比例</th>
                                <th>持股市值</th>
                            </tr>
                        </thead>
                        <tbody>
                            
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="combinedStockShareholdingModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">持股情况</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <table class="table bootstrap-table" id="combinedStockShareholdingModalTable">
                        <thead>
                            <tr>
                                <th data-field="scode" data-sortable="true">股票代码</th>
                                <th data-align="center" data-field="sname" data-sortable="true">股票名称</th>
                                <th data-align="center" data-field="industry" data-sortable="true">所属行业</th>
                                <th data-align="center" data-field="concepts" data-sortable="true" data-formatter="textOverFlowDisplay">概念分类</th>
                                <th data-align="center" data-field="hold_prop" data-sortable="true">持股比例</th>
                                <th data-align="center" data-field="hold_amount" data-sortable="true">持股市值</th>
                            </tr>
                        </thead>
                        <tbody>
                            
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="holdingStocksModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">持股情况</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <table class="table bootstrap-table" id="holdingStocksModalTable">
                        <thead>
                            <tr>
                                <th>股票代码</th>
                                <th>股票名称</th>
                                <th>持股比例</th>
                                <th>市值</th>
                                <th>所属行业</th>
                                <th>所属概念</th>
                            </tr>
                        </thead>
                        <tbody>
                            
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="legendHoldersModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">牛散信息</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <table class="table bootstrap-table" id="legendHoldersModalTable">
                        <thead>
                            <tr>
                                <th>持有人</th>
                                <th>持股比例</th>
                                <th>持股市值</th>
                            </tr>
                        </thead>
                        <tbody>
                            
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <!--div class="modal fade" id="combinedKeywordModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">上传关键词组合</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <table class="table bootstrap-table" id="combinedKeywordModalTable">
                        <thead>
                            <tr>
                                <th data-align="center" data-field="名称" >名称</th>
                                <th data-align="center" data-field="查询关键词" >查询关键词</th>
                                <th data-align="center" data-field="排除关键词" >排除关键词</th>
                            </tr>
                        </thead>
                        <tbody>
                            
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer">
                    {% csrf_token %}
                    <button type="button" class="btn btn-sm btn-primary" data-dismiss="modal" onclick="uploadCombinedKeyword()">提交</button>
                </div>
            </div>
        </div>
    </div-->
    <div class="modal fade" id="combinedKeywordModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">配置关键词组合</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <div class="card">
                        <div class="card-body">
                            <h4 class="text">新增组合
                                 <button class="btn btn-sm" id="addCombine"><i class="fa fa-plus-circle text-primary"></i></button>
                            </h4>
                            <hr>

                            <div id="combinedKeywordList">
                                
                            </div>
                </div>
                <div class="modal-footer">
                    {% csrf_token %}
                    <button type="button" class="btn btn-sm btn-primary" data-dismiss="modal" onclick="uploadCombinedKeyword()">提交</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block jsextend %}
    <script src="/assets/vendor/bootstrap-table/bootstrap-table.min.js"></script>
    <!--script src="/assets/vendor/bootstrap-table/bootstrap-table-mobile.min.js"></script-->
    <script src="/assets/vendor/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>
    <!--script src="/assets/vendor/sheetjs/xlsx.full.min.js"></script-->
{% endblock %}

{% block jsscript %}
<script>
    var top10HolderTableOption = {
        updateUrl: function () { this.url = '/api/top10_holder_data?sort=scode&quarter=' + $('#top10HolderQuarterSelect').val()},
        responseHandler: function (res, jqXHR) {
            for (var idx in res.rows) {
                if ( ! res.rows[idx].industry ){
                    res.rows[idx].industry = '-';
                }

                var propKeys = ['prop_change', 'new_holder_prop', 'new_fund_prop', 'add_holder_prop', 'reduce_holder_prop'];

                for (var i in propKeys) {
                    var key = propKeys[i];
                    res.rows[idx][key] = digitFormatter(res.rows[idx][key]/100, 'percentage4');
                    res.rows[idx][key] = dyeingFormatter(res.rows[idx][key]);
                }
                
            }
            return res;
        
        },
        
        onClickRow: function (row, elem, field) {
            $('#top10HoldersModal').modal('toggle');

            var tableRows = ``;
            
            $.ajax({
                url: '/api/shareholding_data?limit=500&quarter=' + $('#top10HolderQuarterSelect').val() + '&scode=' + row.scode,
                success: function (data){
                    for (var idx in data.rows) {
                        var holder = data.rows[idx];

                        var hold_prop_diff = holder.hold_prop - holder.prev_hold_prop;
                        var hold_amount_diff = holder.hold_amount - holder.prev_hold_amount;

                        hold_prop_disp = digitFormatter(holder.hold_prop / 100, 'percentage4');
                        if (hold_prop_diff != 0) {
                            var hold_prop_disp = `
                                <span class="text-`+ (hold_prop_diff >= 0 ? 'danger' : 'success') +`">
                                    `+ digitFormatter(holder.hold_prop / 100, 'percentage4') + `
                                    (` + (hold_prop_diff >= 0 ? '+': '') + digitFormatter(hold_prop_diff / 100, 'percentage4') + `)
                                </span>
                            `
                        }

                        hold_amount_disp = digitFormatter(holder.hold_amount, 'CNY')
                        if (hold_amount_diff != 0) {
                            var hold_amount_disp = `
                                <span class="text-`+ (hold_amount_diff >= 0 ? 'danger' : 'success') +`">
                                    `+ digitFormatter(holder.hold_amount, 'CNY') + `
                                    (` + (hold_amount_diff >= 0 ? '+': '') + digitFormatter(hold_amount_diff, 'CNY') + `)
                                </span>
                            `
                        }

                        tableRows += `
                            <tr>
                                <td>`+ holder.holder +`</td>
                                <td>`+ hold_prop_disp +`</td>
                                <td>`+ hold_amount_disp +`</td>
                            </tr>
                        `;
                    }
                    $('#top10HoldersModalTable tbody').html(tableRows);
                    $("[data-toggle='popover']").popover();
                }
            });
        },

        align: 'center',
        search: true,
        showRefresh: true,
        showColumns: true,
        iconSize: 'sm',
        // icons: {
        //     refresh: 'glyphicon-repeat',
        //     columns: 'glyphicon-list'
        // },
        classes: 'table',
        toolbar: '#top10-holder-toolbar',

        sortable: true,
        serverSort: true,
        // showMultiSort: true,
        // showMultiSortButton: true,
        
        pagination: true,
        sidePagination: 'server',
        pageSize: 10,
        pageList: [10, 20, 50, 100, 1000],
    };

    var combineStockShareholdingOption = {
        responseHandler: function (res, jqXHR) {
            for (var idx in res.rows) {
                var stock = res.rows[idx];

                var hold_prop_diff = stock.hold_prop - stock.prev_hold_prop;
                var hold_amount_diff = stock.hold_amount - stock.prev_hold_amount;

                if (hold_prop_diff != 0) {
                    stock.hold_prop = `
                        <span class="text-`+ (hold_prop_diff >= 0 ? 'danger' : 'success') +`">
                            `+ digitFormatter(stock.hold_prop / 100, 'percentage4') + `
                            <br>(` + (hold_prop_diff >= 0 ? '+': '') + digitFormatter(hold_prop_diff / 100, 'percentage4') + `)
                        </span>
                    `
                } else {
                    stock.hold_prop = digitFormatter(stock.hold_prop / 100, 'percentage4');
                }
                
                if (hold_amount_diff != 0) {
                    stock.hold_amount = `
                        <span class="text-`+ (hold_amount_diff >= 0 ? 'danger' : 'success') +`">
                            `+ digitFormatter(stock.hold_amount, 'CNY') + `
                            <br>(` + (hold_amount_diff >= 0 ? '+': '') + digitFormatter(hold_amount_diff, 'CNY') + `)
                        </span>
                    `
                } else {
                    stock.hold_amount = digitFormatter(stock.hold_amount, 'CNY')
                }
            }
            return res;
        },
        align: 'center',

        classes: 'table',

        sortable: true,
        serverSort: true,
        
        pagination: true,
        sidePagination: 'server',
        pageSize: 10,
        pageList: [10, 20, 100, 500],
        
        onPostBody: function(data) {$("[data-toggle='popover']").popover();},
    }
    
    var combineHolderTableOption = {
        updateUrl: function () { this.url = '/api/combined_shareholding_data?sort=count&order=desc&quarter=' + $('#combineHolderQuarterSelect').val()},
        responseHandler: function (res, jqXHR) {
            for (var idx in res.rows) {
                var count_diff = res.rows[idx].count - res.rows[idx].last_quarter_count;
                if (count_diff != 0) {
                    res.rows[idx].count = `
                        <span class="text-`+ (count_diff >= 0 ? 'danger' : 'success') +`">
                            `+ res.rows[idx].count + `
                            (` + (count_diff >= 0 ? '+': '') + count_diff + `)
                        </span>
                    `
                }

                var hold_amount_diff = res.rows[idx].hold_amount - res.rows[idx].last_quarter_hold_amount;
                if (hold_amount_diff != 0) {
                    res.rows[idx].hold_amount = `
                        <span class="text-`+ (hold_amount_diff >= 0 ? 'danger' : 'success') +`">
                            `+ digitFormatter(res.rows[idx]['hold_amount'], 'CNY') + `
                            (` + (hold_amount_diff >= 0 ? '+': '') + digitFormatter(hold_amount_diff, 'CNY') + `)
                        </span>
                    `
                }

                res.rows[idx]['added_list'] = res.rows[idx]['added_list'].join('/');
                res.rows[idx]['fixed_list'] = res.rows[idx]['fixed_list'].join('/');
                res.rows[idx]['reduced_list'] = res.rows[idx]['reduced_list'].join('/');
            }
            return res;
        },
        onClickRow: function (row, elem, field) {
            $('#combinedStockShareholdingModal').modal('toggle');

            combineStockShareholdingOption.url = '/api/combined_stock_shareholding_data?sort=hold_amount&order=desc&quarter=' + $('#combineHolderQuarterSelect').val() + '&combine_id=' + row.combine_id;
            $('#combinedStockShareholdingModalTable').bootstrapTable('refreshOptions', combineStockShareholdingOption);
        },

        align: 'center',
        showRefresh: true,
        showColumns: true,
        iconSize: 'sm',

        classes: 'table',
        toolbar: '#combine-holder-toolbar',

        sortable: true,
        serverSort: false,
        
        pagination: true,
        sidePagination: 'local',
        pageSize: 10,
        pageList: [10, 20, 100],
        
        onPostBody: function(data) {$("[data-toggle='popover']").popover();},
    };

    var legendHolderTableOption = {
        updateUrl: function () { this.url = '/api/legend_holder_shareholding_data?sort=count&order=desc&quarter=' + $('#legendHolderQuarterSelect').val()},
        responseHandler: function (res, jqXHR) {
            for (var idx in res.rows) {
                res.rows[idx]['hold_amount'] = digitFormatter(res.rows[idx]['hold_amount'], 'CNY');
            }
            return res;
        },
        onClickRow: function (row, elem, field) {
            $('#holdingStocksModal').modal('toggle');

            var tableRows = ``;
            
            $.ajax({
                url: '/api/shareholding_data?limit=500&quarter=' + $('#legendHolderQuarterSelect').val() + '&holder=' + row.holder,
                success: function (data){
                    for (var idx in data.rows) {
                        var stock = data.rows[idx];

                        var hold_prop_diff = stock.hold_prop - stock.prev_hold_prop;
                        var hold_amount_diff = stock.hold_amount - stock.prev_hold_amount;

                        hold_prop_disp = digitFormatter(stock.hold_prop / 100, 'percentage4');
                        if (hold_prop_diff != 0) {
                            var hold_prop_disp = `
                                <span class="text-`+ (hold_prop_diff >= 0 ? 'danger' : 'success') +`">
                                    `+ digitFormatter(stock.hold_prop / 100, 'percentage4') + `
                                    <br>(` + (hold_prop_diff >= 0 ? '+': '') + digitFormatter(hold_prop_diff / 100, 'percentage4') + `)
                                </span>
                            `
                        }

                        hold_amount_disp = digitFormatter(stock.hold_amount, 'CNY')
                        if (hold_amount_diff != 0) {
                            var hold_amount_disp = `
                                <span class="text-`+ (hold_amount_diff >= 0 ? 'danger' : 'success') +`">
                                    `+ digitFormatter(stock.hold_amount, 'CNY') + `
                                    <br>(` + (hold_amount_diff >= 0 ? '+': '') + digitFormatter(hold_amount_diff, 'CNY') + `)
                                </span>
                            `
                        }

                        tableRows += `
                            <tr>
                                <td>`+ stock.scode +`</td>
                                <td>`+ stock.sname +`</td>
                                <td>`+ hold_prop_disp +`</td>
                                <td>`+ hold_amount_disp +`</td>
                                <td>`+ stock.industry +`</td>
                                <td>`+ textOverFlowDisplay(stock.concepts) +`</td>
                            </tr>
                        `;
                    }
                    $('#holdingStocksModalTable tbody').html(tableRows);
                    $("[data-toggle='popover']").popover();
                }
            })
        },

        align: 'center',
        // search: true,
        // showRefresh: true,
        // showColumns: true,
        iconSize: 'sm',

        classes: 'table',
        toolbar: '#top-legend-holder-toolbar',

        sortable: true,
        serverSort: true,
        
        pagination: true,
        sidePagination: 'server',

        pageSize: 10,
        pageList: [10, 20, 50, 100, 1000],

        formatShowingRows: function(pageFrom, pageTo, totalRows) {return '总共 ' + totalRows + ' 条记录'},
    }

    
    var stockLegendHolderTableOption = {
        updateUrl: function () { this.url = '/api/stock_legend_holder_data?sort=count&order=desc&quarter=' + $('#stockLegendHolderQuarterSelect').val()},

        onClickRow: function (row, elem, field) {
            $('#legendHoldersModal').modal('toggle');

            var tableRows = ``;
            
            $.ajax({
                url: '/api/shareholding_data?limit=500&is_legend=true&quarter=' + $('#stockLegendHolderQuarterSelect').val() + '&scode=' + row.scode,
                success: function (data){
                    for (var idx in data.rows) {
                        var holder = data.rows[idx];

                        var hold_prop_diff = holder.hold_prop - holder.prev_hold_prop;
                        var hold_amount_diff = holder.hold_amount - holder.prev_hold_amount;

                        hold_prop_disp = digitFormatter(holder.hold_prop / 100, 'percentage4');
                        if (hold_prop_diff != 0) {
                            var hold_prop_disp = `
                                <span class="text-`+ (hold_prop_diff >= 0 ? 'danger' : 'success') +`">
                                    `+ digitFormatter(holder.hold_prop / 100, 'percentage4') + `
                                    (` + (hold_prop_diff >= 0 ? '+': '') + digitFormatter(hold_prop_diff / 100, 'percentage4') + `)
                                </span>
                            `
                        }

                        hold_amount_disp = digitFormatter(holder.hold_amount, 'CNY')
                        if (hold_amount_diff != 0) {
                            var hold_amount_disp = `
                                <span class="text-`+ (hold_amount_diff >= 0 ? 'danger' : 'success') +`">
                                    `+ digitFormatter(holder.hold_amount, 'CNY') + `
                                    (` + (hold_amount_diff >= 0 ? '+': '') + digitFormatter(hold_amount_diff, 'CNY') + `)
                                </span>
                            `
                        }

                        tableRows += `
                            <tr>
                                <td>`+ holder.holder +`</td>
                                <td>`+ hold_prop_disp +`</td>
                                <td>`+ hold_amount_disp +`</td>
                            </tr>
                        `;
                    }
                    $('#legendHoldersModalTable tbody').html(tableRows);
                    $("[data-toggle='popover']").popover();
                }
            });
        },
        align: 'center',
        // search: true,
        // showRefresh: true,
        // showColumns: true,
        iconSize: 'sm',

        classes: 'table',
        toolbar: '#stock-legend-holder-toolbar',

        sortable: true,
        serverSort: true,
        
        pagination: true,
        sidePagination: 'server',

        pageSize: 10,
        pageList: [10, 20, 50, 100, 1000],

        onPostBody: function(data) {$("[data-toggle='popover']").popover();},
        formatShowingRows: function(pageFrom, pageTo, totalRows) {return '总共 ' + totalRows + ' 条记录'},
    }   

    /* var combinedKeywordTableOption = {
        data: [],
        align: 'center',
        classes: 'table',
    };
    $('#combineFileChoice').change(function(e) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var data = e.target.result;
            
            var workbook = XLSX.read(data, {
                type: 'binary'
            });
            combinedKeywordTableOption.data = [];
            workbook.SheetNames.forEach(function(sheetName) {
                var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
                XL_row_object.forEach(function(row) {
                    if (row['名称']) {
                        combinedKeywordTableOption.data.push(row);
                    }
                })
                // combinedKeywordTableOption.data = XL_row_object;
            });

            $('#combinedKeywordModal').modal('toggle');
            $('#combinedKeywordModalTable').bootstrapTable('refreshOptions', combinedKeywordTableOption);
        }
        reader.onerror = function(ex) {
            console.log(ex);
        };
        reader.readAsBinaryString(e.target.files[0]);
    }); */

    /* var uploadCombinedKeyword = function() {
        $.ajax({
            url: '/api/update_combine_keywords_data',
            method: 'post',
            beforeSend: function (xhr, settings){
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", $('[name=csrfmiddlewaretoken]').val());
                }
            },
            contentType: 'application/json',
            data: JSON.stringify({
                'keywords': combinedKeywordTableOption.data,
                // 'csrfmiddlewaretoken': $('[name=csrfmiddlewaretoken]').val(),
            }),
            success: function () {
                $('#combine-holder-table').bootstrapTable('refreshOptions', combineHolderTableOption);
                $('#combineFileChoice').val('');
            },
            error: function (e) {
                console.log(e);
                $('#combineFileChoice').val('');
            }
        });
    } */

    var addKeywordCombine = function (name='', keywords='', excludeKeywords='') {
        $('#combinedKeywordList').append(`
        <div class="row combinedKeywordContainer">
            <div class="col col-md-2">
                <input type="input" class="form-control form-control-sm" name="name" value="` + name + `" placeholder="组合名">
            </div>
            <div class="">
                <a class="h4">:</a>
            </div>
            <div class="col col-md-4">
                <input type="input" class="form-control form-control-sm" name="keywords" value="` + keywords + `" placeholder="关键词">
            </div>
            <div class="col col-md-4">
                <input type="input" class="form-control form-control-sm" name="excludeKeywords" value="` + excludeKeywords + `" placeholder="排除关键词">
            </div>
            <div class="col col-md-1">
                <button class="btn btn-sm filter-rm-arg" onclick="$(this).parents('.combinedKeywordContainer').remove()"><i class="fa fa-times text-danger"></i></button>
            </div>
        </div>
        `);
    }
    $('#addCombine').click(function() {addKeywordCombine('','','')});
    var initializeCombinedKeywords = function () {
        $.ajax({
            url: '/api/combine_keywords_data?limit=10000',
            success: function (res){
                var data = res.rows;

                $('.combinedKeywordContainer').remove();
                for (var i in data) {
                    var row = data[i];

                    addKeywordCombine(
                        row.cname,
                        row.keyword_list.join(','),
                        row.exclude_keyword_list.join(','),
                    )
                }
            }
        });

        $('#combinedKeywordModal').modal('toggle');
    }

    var uploadCombinedKeyword = function() {
        var keywordsData = [];

        var $containers = $('.combinedKeywordContainer');

        $containers.each(function() {
            keywordsData.push({
                name: $(this).find('input[name="name"]').val(),
                keywords: $(this).find('input[name="keywords"]').val(),
                excludeKeywords: $(this).find('input[name="excludeKeywords"]').val()
            });
        });

        $.ajax({
            url: '/api/combine_keywords_data',
            method: 'post',
            beforeSend: function (xhr, settings){
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", $('[name=csrfmiddlewaretoken]').val());
                }
            },
            contentType: 'application/json',
            data: JSON.stringify({
                'keywords': keywordsData,
            }),
            success: function () {
                $('#combine-holder-table').bootstrapTable('refreshOptions', combineHolderTableOption);
            },
        });
    } 

    top10HolderTableOption.updateUrl();
    combineHolderTableOption.updateUrl();
    legendHolderTableOption.updateUrl();
    stockLegendHolderTableOption.updateUrl();
    $('#top10-holder-table').bootstrapTable(top10HolderTableOption);
    $('#combine-holder-table').bootstrapTable(combineHolderTableOption);
    $('#holder-shareholding-table').bootstrapTable(legendHolderTableOption);
    $('#stock-legend-holder-table').bootstrapTable(stockLegendHolderTableOption);
    
    $('#combinedStockShareholdingModalTable').bootstrapTable(combineStockShareholdingOption);
    // $('#combinedKeywordModalTable').bootstrapTable(combinedKeywordTableOption);

    $('#top10HolderQuarterSelect').change(function () {
        top10HolderTableOption.updateUrl();
        $('#top10-holder-table').bootstrapTable('refreshOptions', top10HolderTableOption);
    });
    $('#combineHolderQuarterSelect').change(function () {
        combineHolderTableOption.updateUrl();
        $('#combine-holder-table').bootstrapTable('refreshOptions', combineHolderTableOption);
    });
    $('#legendHolderQuarterSelect').change(function () {
        legendHolderTableOption.updateUrl();
        $('#holder-shareholding-table').bootstrapTable('refreshOptions', legendHolderTableOption);
    });
    $('#stockLegendHolderQuarterSelect').change(function () {
        stockLegendHolderTableOption.updateUrl();
        $('#stock-legend-holder-table').bootstrapTable('refreshOptions', stockLegendHolderTableOption);
    });

    searchInputPopover();
</script>
{% endblock %}